package view {
	import flash.display.Sprite;
	import flash.events.MouseEvent;
	import fs.message.MessageTransmitter;
	import message.GameMessage;
	import model.PiecesDefination;
	import model.Player;
	
	/**
	 * ...
	 * @author flyingSnow
	 */
	public class PiecesList extends Sprite implements IPlayerView{
		private var _piecesList:Array;
		private var _colorIndex:int;
		
		private const PIECES_POS:Array = [  [0, 0], //一格
											[0, 2], //两格
											[2, 0], //三格
											[0, 5], //三格拐角
											[7, 0], //四格
											[3, 4], //四格折尺
											[4, 0], //四格丁字
											[8, 6], //四格方块
											[5, 5], //四格Z字
											[9, 0], //五格
											[11, 0],//五格折尺 
											[14, 0],//五格2-3Z字 
											[11, 5],//五格b字 
											[14, 5],//五格凹字 
											[17, 0],//五格戈形
											[19, 0],//五格T形 
											[17, 5],//五格L形 
											[22, 0],//五格W形 
											[26, 0],//五格Z形 
											[21, 4],//五格飞形
											[25, 4] //五格十字
											];
		
		public function PiecesList() {
			addPieces();
		}
		
		private function addPieces():void {
			_piecesList = [];
			for (var index:String in PiecesDefination.PIECES_DEF) {
				var piece:Piece = new Piece();
				piece.x = PIECES_POS[index][0]*Square.STANDARD_SIZE;
				piece.y = PIECES_POS[index][1]*Square.STANDARD_SIZE;
				piece.crntColorIndex = 1;
				piece.shapeArray(int(index), 1);
				piece.addEventListener(MouseEvent.MOUSE_DOWN, onClick);
				addChild(piece);
				_piecesList.push(piece);
			}
		}
		
		private function onClick(e:MouseEvent):void {
			var crntPiece:Piece = e.currentTarget as Piece;
			if (crntPiece.crntColorIndex != Square.UNABLED_INDEX) {
				MessageTransmitter.transmitMessage(GameMessage.SELECT_PIECE, {index:crntPiece.pieceIndex } );
			}
		}
		
		public function update(player:Player):void {
			for (var strIndex:String in _piecesList) {
				var crntPiece:Piece = _piecesList[strIndex] as Piece;
			
				if (player.hasUsedPiece(int(strIndex))) {
					crntPiece.visible = false;
				}else if(!player.getRecentlyUsable(int(strIndex))){
					crntPiece.crntColorIndex = Square.UNABLED_INDEX;
				}else {
					crntPiece.crntColorIndex = _colorIndex;
				}
			}
		}
		
		public function set colorIndex(value:int):void {
			_colorIndex = value;
			for each(var piece:Piece in _piecesList) {
				piece.crntColorIndex = _colorIndex;
			}
		}
	}

}